package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {


    @Autowired
    private RestHighLevelClient client;

    /**
     * 自动补全
     *
     * @param key
     * @return
     */
    @Override
    public List<String> getSuggestions(String key) {
        //得到request对象
        SearchRequest request = new SearchRequest("hotel");
        //设置参数
        request.source().suggest(
                new SuggestBuilder().addSuggestion("hotelSuggestion",
                        SuggestBuilders.completionSuggestion("suggestion")
                                .prefix(key).skipDuplicates(true)
                                .size(10))
        );

        try {
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析数据
            Suggest suggest = response.getSuggest();
            //根据名称获取补全结果
            CompletionSuggestion suggestion = suggest.getSuggestion("hotelSuggestion");
            //获取option
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            //初始化集合
            ArrayList<String> list = new ArrayList<>();
            //遍历取出数据
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().string();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("操作失败");
        }
        return new ArrayList<>();
    }



    /**
     * 关键字搜索和分页
     *
     * @param params
     * @return
     */
    @Override
    public PageResult getPageResult(RequestParams params) {
        //获取request对象
        SearchRequest request = new SearchRequest("hotel");
        //设置参数
        //1.关键字查询
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        if (StringUtils.isEmpty(params.getKey())) {
            query.must(QueryBuilders.matchAllQuery());
        } else {
            query.must(QueryBuilders.matchQuery("all", params.getKey()));
        }
        //3.过滤
        if (!StringUtils.isEmpty(params.getBrand())) {
            query.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (!StringUtils.isEmpty(params.getCity())) {
            query.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        if (!StringUtils.isEmpty(params.getStarName())) {
            query.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        if (params.getMaxPrice() != null || params.getMinPrice() != null)
            query.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice())
                    .lte(params.getMaxPrice()));
        //function score增加广告权重
        String script = "return doc['adPrice'].value"; //按照广告分数排名
        FunctionScoreQueryBuilder query1 = QueryBuilders.functionScoreQuery(query,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                //ScoreFunctionBuilders.weightFactorFunction(5)
                                ScoreFunctionBuilders.scriptFunction(new Script(script))

                        ),

                });

        request.source().query(query);
        request.source().highlighter(new HighlightBuilder().field("name")
                .requireFieldMatch(false));
        request.source().query(query1);

        //按照地理位置排序
        if (!StringUtils.isEmpty(params.getLocation())) {
            request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(params.getLocation())).
                    order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
        }

        if (!StringUtils.isBlank(params.getSortBy()) && !params.getSortBy().equals("default")) {
            String[] split = params.getSortBy().split("-");
            request.source().sort(split[0], SortOrder.fromString(split[1]));
        }

        //2.分页
        request.source().from((params.getPage() - 1) * params.getSize())
                .size(params.getSize());
        //发送请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //总记录数
            Long total = response.getHits().getTotalHits().value;
            //分页结果封装
            ArrayList<HotelDoc> list = new ArrayList<>();
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                //得到source对象
                String source = hit.getSourceAsString();
                HotelDoc hotelDoc = JSON.parseObject(source, HotelDoc.class);
                //获取highlight
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    HighlightField field = highlightFields.get("name");
                    if (field != null) {
                        Text[] fragments = field.getFragments();
                        //将数组转化为字符串
                        if (fragments != null && fragments.length > 0) {
                            String join = StringUtils.join(fragments);
                            hotelDoc.setName(join);
                        }
                    }
                }
                //获得sort距离值
                Object[] sortValues = hit.getSortValues();
                if (sortValues.length > 0) {
                    Object sortValue = sortValues[0];
                    hotelDoc.setDistance(sortValue);
                }
                list.add(hotelDoc);
            }

            return PageResult.builder().total(total).hotels(list).build();
        } catch (IOException e) {
            log.error("发送失败");
        }
        return null;
    }

    /**
     * 动态获取页面参数(聚合函数)
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {

        //得到request对象
        SearchRequest request = new SearchRequest("hotel");
        //设置参数
        buildBasicQuery(params, request);
        //设置size
        request.source().size(0);
        //1.品牌聚合
        request.source().aggregation(AggregationBuilders.
                        terms("brandAgg")
                        .order(BucketOrder.count(true))
                        .field("brand"))
                .size(20);
        //2.城市聚合
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .order(BucketOrder.count(true))
                .field("city")
                .size(20)
        );
        //3.星级聚合
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .order(BucketOrder.count(true))
                .field("starName")
                .size(20)
        );


        //发送请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Aggregations Aggregations = response.getAggregations();
            HashMap<String, List<String>> map = new HashMap<>();
            if (Aggregations != null) {
                //1.根据品牌获取聚合结果
                Terms brandAgg = Aggregations.get("brandAgg");
                if (brandAgg != null) {
                    List<? extends Terms.Bucket> brandBuckets = brandAgg.getBuckets();
                    ArrayList<String> list = new ArrayList<>();
                    for (Terms.Bucket bucket : brandBuckets) {
                        String key = bucket.getKeyAsString();
                        list.add(key);
                    }
                    map.put("brand", list);
                }

                //2.根据城市获取聚合结果

                Terms cityAgg = Aggregations.get("cityAgg");
                if (cityAgg != null) {
                    List<? extends Terms.Bucket> cityBuckets = cityAgg.getBuckets();
                    ArrayList<String> list1 = new ArrayList<>();
                    for (Terms.Bucket bucket : cityBuckets) {
                        String key = bucket.getKeyAsString();
                        list1.add(key);
                    }
                    map.put("city", list1);
                }


                //3.根据星级获取聚合结果
                Terms starAgg = Aggregations.get("starAgg");
                if (starAgg != null) {
                    List<? extends Terms.Bucket> starBuckets = starAgg.getBuckets();
                    ArrayList<String> list2 = new ArrayList<>();
                    for (Terms.Bucket bucket : starBuckets) {
                        String key = bucket.getKeyAsString();
                        list2.add(key);
                    }
                    map.put("starName", list2);
                }

                return map;
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("操作失败");
        }
        return new HashMap<>();
    }

    /**
     * 构建查询条件
     *
     * @param params
     * @param request
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //1 构建查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 按照关键词查询
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        //1.2 条件过滤
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gt(minPrice).lte(maxPrice));
        }

        //*** 广告算分
        String script = "return doc['adPrice'].value"; // 按照广告分数排名
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                QueryBuilders.functionScoreQuery(boolQuery,
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        QueryBuilders.termQuery("isAD", true),
                                        //ScoreFunctionBuilders.weightFactorFunction(10)
                                        ScoreFunctionBuilders.scriptFunction(new Script(script))
                                )
                        }
                );

        request.source()
                .query(functionScoreQueryBuilder)
                //分页
                .from((params.getPage() - 1) * params.getSize())
                .size(params.getSize())
                .trackTotalHits(true);
    }
}
